/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
 var serialize = function(root) {
  if(!root) return '';
  const toList = (node) => {
      return [node.val, ...(node.left ? toList(node.left) : []), ...(node.right ? toList(node.right) : [])];
  }
  return toList(root).join(',');
};

/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
  const nodes = data ? data.split(',').map(e => parseInt(e)) : [];
  const buildTree = (l, r) => {
      if(l === r) return null;
      const val = nodes[l];
      let i = l + 1;
      while(i < r && nodes[i] < nodes[l]) {
          i++;
      }
      return {
          val,
          left: buildTree(l + 1, i),
          right: buildTree(i, r)
      };
  }
  return buildTree(0, nodes.length);
};

/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/